<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
/**
 * 项目
 *
 * @icon fa fa-circle-o
 */
class Product extends Backend
{

    /**
     * Product模型对象
     * @var \app\admin\model\Product
     */
    protected $model = null;
    protected $noNeedRight = ['getcar','export','export2'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Product;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("isDelList", $this->model->getIsDelList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $admininfo=$this->auth->getUserInfo();
            $where_admin=[];
            if($admininfo['store_id'])
            {
                $where_admin['store_id']=$admininfo['store_id'];
            }
            $list = $this->model
                    ->with(['store'])
                    ->where($where)
                    ->where($where_admin)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('store')->visible(['store_name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    public function add()
    {
        if (false === $this->request->isPost()) {
            $admininfo=$this->auth->getUserInfo();
            $this->assign('admininfo',$admininfo);
            $this->assign('store_id',$admininfo['store_id']);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            $admininfo=$this->auth->getUserInfo();
            if($admininfo['store_id']>0)
            {
                $params['store_id']=$admininfo['store_id'];
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $row['imagelist']=explode(',',$row['images']);
            $this->view->assign('row', $row);
            $admininfo=$this->auth->getUserInfo();
            $this->assign('admininfo',$admininfo);
            $this->assign('store_id',$admininfo['store_id']);
            $change_info=db('change_log')->where(['type'=>'3','change_id'=>$ids])->order('id desc')->find();
            $change_images=[];
            if($change_info)
            {
                $change_images=$change_info['change_images'];
                if($change_images)
                {
                    $change_images=explode(',',$change_images);
                }
            }
            
            $this->assign('change_images',$change_images);
            $this->assign('change_info',$change_info);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            
            $admininfo=$this->auth->getUserInfo();
            $store_id=$admininfo['store_id'];
            
            
            //如果信息是正在审核中的，禁止修改
            if(($row['status']=='1' || $row['status']=='2') && $store_id>0)
            {
                $this->error(__('审核中不可修改', ''));
            }
            if($store_id==0)
            {
                if(isset($params['status'])=='1' && $row['status']=='2')
                {
                    //通过,如果有申请中的变更记录，需要更改状态
                    $change_info=db('change_log')->where(['type'=>'3','change_id'=>$ids,'status'=>'2'])->find();
                    // if(isset($change_info['change_images']) && $change_info['change_images'])
                    // {
                    //     $params['images']=$row['images'].','.$change_info['change_images'];
                    // }
                    db('change_log')->where(['id'=>$change_info['id']])->update(['status'=>'1']);
    
                }
                if(isset($params['status'])=='4' && $row['status']=='2')
                {
                    //未通过,如果有申请中的变更记录，需要更改状态
                    $change_info=db('change_log')->where(['type'=>'3','change_id'=>$ids,'status'=>'2'])->find();
                    db('change_log')->where(['id'=>$change_info['id']])->update(['status'=>'4']);
                }
            }
            else
            {
                $params['status']='2';
            }
            
            if(isset($params['change_title']))
            {
                $change_title=$params['change_title'];
                $change_images=$params['change_images'];
                unset($params['change_title']);
                unset($params['change_images']);
                
                $result_data['type']='3';
                $result_data['change_id']=$row['id'];
                $result_data['change_title']=$change_title;
                $result_data['change_images']=$change_images;
                $result_data['add_time']=time();
                $change_result=db('change_log')->insert($result_data);
            }
            
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    function getcar()
    {
        $admininfo=$this->auth->getUserInfo();
        $store_id=$admininfo['store_id'];
        $ids=$this->request->post('product_id');
        $select_car=[];
        if($ids)
        {
           
            $car_ids=$this->model->where(['id'=>$ids])->value('car_ids');
           
            $car_idarr=explode(',',$car_ids);
            if($admininfo['store_id'])
            {
                $select_car=db('car')->where(['id'=>['in',$car_ids]])->orderRaw("FIELD(store_id, $store_id) DESC, store_id ASC")->select();
                $result=db('car')->where(['is_del'=>0,'status'=>3])->whereor(['id'=>['in',$car_ids]])->orderRaw("FIELD(store_id, $store_id) DESC, store_id ASC")->select();
            }
            else
            {
                $select_car=db('car')->where(['id'=>['in',$car_ids]])->orderRaw("store_id ASC")->select();
                $result=db('car')->where(['is_del'=>0,'status'=>3])->whereor(['id'=>['in',$car_ids]])->orderRaw("store_id ASC")->select();
            }
            
            
            // $result=db('car')->where(['id'=>['not in',$car_ids],'is_del'=>0])->orderRaw("FIELD(store_id, $store_id) DESC, store_id ASC")->select();
            
            //判断在不在右侧
            foreach ($result as $key => &$value) {
                # code...
                $value['ischeck']=0;
                
                if(in_array($value['id'],$car_idarr))
                {
                    $value['ischeck']=1;
                }
            }
        }
        else
        {
            if($admininfo['store_id'])
            {
                $result=db('car')->where(['is_del'=>0])->orderRaw("FIELD(store_id, $store_id) DESC, store_id ASC")->select();
            }
            else
            {
                $result=db('car')->where(['is_del'=>0])->orderRaw("store_id ASC")->select();
            }
            
        }
        $data['carlist']=$result;
        $data['select_car']=$select_car;
        
        return json($data);
    }
    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();
        foreach ($list as $key => $value) {
            # code...
            if(($value['status']=='1' || $value['status']=='2'))
            {
                $this->error(__($value['title'].'正在审核中不可删除', ''));
            }
        }
        $count = 0;
        Db::startTrans();
        try {
            
            $res=$this->model->where($pk, 'in', $ids)->update(['is_del'=>'1','status'=>'2']);
            $idsarr=explode(',',$ids);
            // var_dump($idsarr);die;
            foreach ($idsarr as $key => $value) {
                # code...
                $change_title='项目删除';
                
                $result_data['type']='3';
                $result_data['change_id']=$value;
                $result_data['change_title']=$change_title;
                $result_data['add_time']=time();
                $insertall[]=$result_data;
                
            }
            if($insertall)
            {
                $change_result=db('change_log')->insertAll($insertall);
            }
            
            
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($res) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    //按日期导出
    public function export2()
    {
        $search = $this->request->post('search');
        $ids = $this->request->post('ids');
        $filter = $this->request->post('filter');
        $op = $this->request->post('op');
        $columns = $this->request->post('columns');
        $this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]);
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();


        $admininfo=$this->auth->getUserInfo();
        $where_admin=[];
        if($admininfo['store_id'])
        {
            $where_admin['store_id']=$admininfo['store_id'];
        }
        $count=$this->model               
                ->where($where)
                ->where($where_admin)
                ->count();
        // var_dump($count);die;
        $p=$offset/$limit;
        $p=$p+1;
        $list = $this->model      
                ->alias('p')    
                ->join('store s','p.store_id=s.id','left') 
                ->where($where)
                ->where($where_admin)
                ->order('authen_time_zj', 'desc')
                ->field('p.*,s.store_name,s.name')
                ->select();
     
   
            vendor('PHPExcel.PHPExcel');
            //添加标题到数组头部
            $file_name = '项目列表' . date('Y-m-d_His') . '.xls';
            $PHPExcel = new \PHPExcel();
            // print_r($PHPExcel);die;
            
            $PHPSheet = $PHPExcel->getActiveSheet();
            // 设置A列的宽度为20
            //    $PHPSheet->getColumnDimension('A')->setWidth(30);
           // 设置B列的宽度为30
        //    $PHPSheet->getColumnDimension('B')->setWidth(30);
           $PHPSheet->getColumnDimension('C')->setWidth(20);
           $PHPSheet->getColumnDimension('D')->setWidth(20);
           $PHPSheet->getColumnDimension('E')->setWidth(20);
           $PHPSheet->getColumnDimension('F')->setWidth(20);
           $PHPSheet->getColumnDimension('G')->setWidth(50);
           $PHPSheet->getColumnDimension('J')->setWidth(30);
           $PHPSheet->getColumnDimension('K')->setWidth(30);
           $PHPSheet->getColumnDimension('O')->setWidth(30);
           $PHPSheet->getColumnDimension('P')->setWidth(30);
           $PHPSheet->getColumnDimension('R')->setWidth(30);
           $PHPSheet->getColumnDimension('L')->setWidth(30);
           $PHPSheet->getColumnDimension('M')->setWidth(30);
            $PHPSheet->setTitle("表格一");
            
           
            $PHPSheet->setCellValue("A1", "运输备案台账");
            $PHPSheet->mergeCells('A1:S1'); 
            $styleArray = array(  
                'alignment' => array(  
                    'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,  
                    'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,  
                    'wrap' => true, // 设置自动换行 
                ),  
            );  
            $PHPSheet->getStyle('A1')->applyFromArray($styleArray);  

            $PHPSheet->mergeCells('A2:A3'); 
            $PHPSheet->mergeCells('B2:B3'); 
            $PHPSheet->mergeCells('C2:C3'); 
            $PHPSheet->mergeCells('D2:D3'); 


            $PHPSheet->mergeCells('I2:I3'); 
            $PHPSheet->mergeCells('J2:J3'); 
            $PHPSheet->mergeCells('K2:K3'); 
            $PHPSheet->mergeCells('L2:L3'); 
            $PHPSheet->mergeCells('M2:M3'); 
            $PHPSheet->mergeCells('N2:N3'); 
            $PHPSheet->mergeCells('O2:O3'); 
            $PHPSheet->mergeCells('P2:P3'); 



            $PHPSheet->mergeCells('E2:F2'); 
            $PHPSheet->mergeCells('G2:H2'); 
            $PHPSheet->mergeCells('Q2:R2'); 

            $PHPSheet->setCellValue("A2", "序号");
            $PHPSheet->setCellValue("B2", "审核通过日期");
            $PHPSheet->setCellValue("C2", "项目");
            $PHPSheet->setCellValue("D2", "地址");
            $PHPSheet->setCellValue("E2", "建设单位信息");
            // $PHPSheet->setCellValue("F2", "");
            $PHPSheet->setCellValue("G2", "运输单位信息");
            // $PHPSheet->setCellValue("H2", "运输单位信息");
            $PHPSheet->setCellValue("I2", "经办人");
            $PHPSheet->setCellValue("J2", "联系电话");
            $PHPSheet->setCellValue("K2", "建筑垃圾种类");
            $PHPSheet->setCellValue("L2", "拟处置方量");
            $PHPSheet->setCellValue("M2", "处理地点");
            $PHPSheet->setCellValue("N2", "运输路线");
            $PHPSheet->setCellValue("O2", "处置开始日期");
            $PHPSheet->setCellValue("P2", "处置截止日期");

            $PHPSheet->setCellValue("Q2", "车辆数量");
            // $PHPSheet->setCellValue("R2", "车辆信息");
            $PHPSheet->setCellValue("S2", "备注");

            $PHPSheet->setCellValue("E3", "建设单位");
            $PHPSheet->setCellValue("F3", "法人");
            $PHPSheet->setCellValue("G3", "运输单位");
            $PHPSheet->setCellValue("H3", "法人");
            $PHPSheet->setCellValue("Q3", "车辆数量");
            $PHPSheet->setCellValue("R3", "车辆信息");
            $i = 4;
           // dump($res);die;
            $lastStoreName = '';
            $startRow = 4;  
            // $styleArray = array(  
            //     'alignment' => array(  
            //         'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,  
            //         'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,  
            //     ),  
            // );  
             
            foreach ($list as $keys => $value) {  
                //查询车辆信息
                $carlist=db('car')->where(['id'=>['in',$value['car_ids']]])->select();
                $plate_number=[];
                foreach ($carlist as $k => $v) {
                    # code...
                    $plate_number[]=$v['plate_number'];
                    
                    
                }  
                $values['authen_time_zj']=empty($value['edit_time'])?'':date('Y-m-d H:i:s',$value['authen_time_zj']);
                $PHPSheet->setCellValue('A' . $i, '' . $keys+1);
                $PHPSheet->setCellValue('B' . $i, '' . $values['authen_time_zj']);
                $PHPSheet->setCellValue('C' . $i, '' . $value['title']);
                $PHPSheet->setCellValue('D' . $i, '' . $value['address']);
                $PHPSheet->setCellValue('E' . $i, '' . $value['jianshe_company']);
                
                // $currentStoreName = $value['store_id'];  
                // if ($currentStoreName != $lastStoreName && !empty($lastStoreName)) {  
                //     // 如果当前store_name和上一个不同，并且上一个不是空的，则合并上一个的单元格  
                //     $PHPSheet->mergeCells('F' . $startRow . ':' . 'F' . ($i - 1));  

                    
                //     $PHPSheet->getStyle('F' . $startRow)->applyFromArray($styleArray); 


                //     $startRow = $i; // 重置起始行  
                // }  
                // $lastStoreName = $currentStoreName; 
                $PHPSheet->setCellValue('F' . $i, '' . $value['jianshe_name']);
                $PHPSheet->setCellValue('G' . $i, '' . $value['store_name']);
                $PHPSheet->setCellValue('H' . $i, '' . $value['name']);
                $PHPSheet->setCellValue('I' . $i, '' . $value['manager']);
                $PHPSheet->setCellValue('J' . $i, '' . $value['contact_tel']);
                $PHPSheet->setCellValue('K' . $i, '' . $value['waste_type'].' ');
                $PHPSheet->setCellValue('L' . $i, '' . $value['waste_count']);
                $PHPSheet->setCellValue('M' . $i, '' . $value['disposal_sites']);
                $PHPSheet->setCellValue('N' . $i, '' . $value['routes']);
                $PHPSheet->setCellValue('O' . $i, '' . $value['start_time']);
                $PHPSheet->setCellValue('P' . $i, '' . $value['end_time']);
                $PHPSheet->setCellValue('Q' . $i, '' . count($plate_number));
                $PHPSheet->setCellValue('R' . $i, '' . implode(',',$plate_number));
                for ($col = 'A'; $col <= 'S'; $col++) {  
                    // 设置单元格的自动换行样式  
                    $PHPSheet->getStyle($col . $i)->applyFromArray($styleArray); 
                    $PHPSheet->getStyle($col . $i)->applyFromArray($styleArray); 
                }  
                
                $i++;
            }
            for ($col = 'A'; $col <= 'S'; $col++) {  
                // 设置单元格的自动换行样式  
                $PHPSheet->getStyle($col . 2)->applyFromArray($styleArray); 
                $PHPSheet->getStyle($col . 3)->applyFromArray($styleArray); 
            }  
            // 最后，检查最后一个store_name的单元格是否需要合并（如果列表不以不同的store_name结束）  
            // if ($lastStoreName != '') {  
            //     $PHPSheet->mergeCells('F' . $startRow . ':' . 'F' . ($i - 1));  
            //     $PHPSheet->getStyle('F' . $startRow)->applyFromArray($styleArray); 
            // }  
           
            $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, "Excel2007");
            header('Content-Disposition: attachment;filename=' . $file_name);
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            $PHPWriter->save("php://output");
   
       
    }
    //按企业
    public function export()
    {
        $search = $this->request->post('search');
        $ids = $this->request->post('ids');
        $filter = $this->request->post('filter');
        $op = $this->request->post('op');
        $columns = $this->request->post('columns');
        $this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]);
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();


        $admininfo=$this->auth->getUserInfo();
        $where_admin=[];
        if($admininfo['store_id'])
        {
            $where_admin['store_id']=$admininfo['store_id'];
        }
        $count=$this->model               
                ->where($where)
                ->where($where_admin)
                ->count();
        // var_dump($count);die;
        $p=$offset/$limit;
        $p=$p+1;
        $list = $this->model      
                ->alias('p')    
                ->join('store s','p.store_id=s.id','left') 
                ->where($where)
                ->where($where_admin)
                ->order('store_id', 'asc')
                ->field('p.*,s.store_name,s.name')
                ->select();
     
   
            vendor('PHPExcel.PHPExcel');
            //添加标题到数组头部
            $file_name = '项目列表' . date('Y-m-d_His') . '.xls';
            $PHPExcel = new \PHPExcel();
            // print_r($PHPExcel);die;
            
            $PHPSheet = $PHPExcel->getActiveSheet();
            // 设置A列的宽度为20
            //    $PHPSheet->getColumnDimension('A')->setWidth(30);
           // 设置B列的宽度为30
        //    $PHPSheet->getColumnDimension('B')->setWidth(30);
           $PHPSheet->getColumnDimension('C')->setWidth(20);
           $PHPSheet->getColumnDimension('D')->setWidth(20);
           $PHPSheet->getColumnDimension('E')->setWidth(20);
           $PHPSheet->getColumnDimension('F')->setWidth(20);
           
           $PHPSheet->getColumnDimension('G')->setWidth(50);
           $PHPSheet->getColumnDimension('J')->setWidth(20);
           $PHPSheet->getColumnDimension('K')->setWidth(30);
           $PHPSheet->getColumnDimension('O')->setWidth(30);
           $PHPSheet->getColumnDimension('P')->setWidth(30);
           $PHPSheet->getColumnDimension('R')->setWidth(50);
           $PHPSheet->getColumnDimension('L')->setWidth(30);
           $PHPSheet->getColumnDimension('M')->setWidth(30);
            $PHPSheet->setTitle("表格一");
            
           
            $PHPSheet->setCellValue("A1", "运输备案台账");

            $styleArray = array(  
                'alignment' => array(  
                    'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,  
                    'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,  
                    'wrap' => true, // 设置自动换行 
                ),  
            );  
            $PHPSheet->getStyle('A1')->applyFromArray($styleArray);  
            $PHPSheet->mergeCells('A1:S1'); 

            $PHPSheet->mergeCells('A2:A3'); 
            $PHPSheet->mergeCells('B2:B3'); 
            $PHPSheet->mergeCells('C2:C3'); 
            $PHPSheet->mergeCells('D2:D3'); 
            $PHPSheet->mergeCells('E2:E3');


            $PHPSheet->mergeCells('I2:I3'); 
            $PHPSheet->mergeCells('J2:J3'); 
            $PHPSheet->mergeCells('K2:K3'); 
            $PHPSheet->mergeCells('L2:L3'); 
            $PHPSheet->mergeCells('M2:M3'); 
            $PHPSheet->mergeCells('N2:N3'); 
            $PHPSheet->mergeCells('O2:O3'); 
            $PHPSheet->mergeCells('P2:P3'); 

            $PHPSheet->mergeCells('F2:G2'); 
            $PHPSheet->mergeCells('Q2:R2'); 

            $PHPSheet->setCellValue("A2", "序号");
            $PHPSheet->setCellValue("B2", "运输单位");
            $PHPSheet->setCellValue("C2", "项目");
            $PHPSheet->setCellValue("D2", "地址");
            $PHPSheet->setCellValue("E2", "审核通过日期");
            $PHPSheet->setCellValue("F2", "建设单位信息");
            // $PHPSheet->setCellValue("G2", "运输单位信息");
            $PHPSheet->setCellValue("H2", "运输单位信息");


            $PHPSheet->setCellValue("I2", "经办人");
            $PHPSheet->setCellValue("J2", "联系电话");
            $PHPSheet->setCellValue("K2", "建筑垃圾种类");
            $PHPSheet->setCellValue("L2", "拟处置方量");
            $PHPSheet->setCellValue("M2", "处理地点");
            $PHPSheet->setCellValue("N2", "运输路线");
            $PHPSheet->setCellValue("O2", "处置开始日期");
            $PHPSheet->setCellValue("P2", "处置截止日期");

            $PHPSheet->setCellValue("Q2", "车辆数量");
            // $PHPSheet->setCellValue("R2", "车辆信息");
            $PHPSheet->setCellValue("S2", "备注");

            // $PHPSheet->setCellValue("E3", "建设单位");
            $PHPSheet->setCellValue("F3", "建设单位");
            $PHPSheet->setCellValue("G3", "法人");
            $PHPSheet->setCellValue("H3", "法人");
            $PHPSheet->setCellValue("Q3", "车辆数量");
            $PHPSheet->setCellValue("R3", "车辆信息");
            $i = 4;
           // dump($res);die;
            $lastStoreName = '';
            $startRow = 4;  
            // $styleArray = array(  
            //     'alignment' => array(  
            //         'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,  
            //         'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,  
            //     ),  
            // );  
             
            foreach ($list as $keys => $value) {  
                //查询车辆信息
                $carlist=db('car')->where(['id'=>['in',$value['car_ids']]])->select();
                $plate_number=[];
                foreach ($carlist as $k => $v) {
                    # code...
                    $plate_number[]=$v['plate_number'];
                    
                    
                }  
                $values['authen_time_zj']=empty($value['edit_time'])?'':date('Y-m-d H:i:s',$value['authen_time_zj']);
                $PHPSheet->setCellValue('A' . $i, '' . $keys+1);
                $PHPSheet->setCellValue('B' . $i, '' . $value['store_name']);
                $PHPSheet->setCellValue('C' . $i, '' . $value['title']);
                $PHPSheet->setCellValue('D' . $i, '' . $value['address']);
                $PHPSheet->setCellValue('E' . $i, '' . $values['authen_time_zj']);
                
                $currentStoreName = $value['store_id'];  
                if ($currentStoreName != $lastStoreName && !empty($lastStoreName)) {  
                    // 如果当前store_name和上一个不同，并且上一个不是空的，则合并上一个的单元格  
                    $PHPSheet->mergeCells('B' . $startRow . ':' . 'B' . ($i - 1));  

                    
                    $PHPSheet->getStyle('B' . $startRow)->applyFromArray($styleArray); 


                    $startRow = $i; // 重置起始行  
                }  
                $lastStoreName = $currentStoreName; 
                $PHPSheet->setCellValue('F' . $i, '' . $value['jianshe_company']);
                $PHPSheet->setCellValue('G' . $i, '' . $value['jianshe_name']);
                $PHPSheet->setCellValue('H' . $i, '' . $value['name']);
                $PHPSheet->setCellValue('I' . $i, '' . $value['manager']);
                $PHPSheet->setCellValue('J' . $i, '' . $value['contact_tel']);
                $PHPSheet->setCellValue('K' . $i, '' . $value['waste_type'].' ');
                $PHPSheet->setCellValue('L' . $i, '' . $value['waste_count']);
                $PHPSheet->setCellValue('M' . $i, '' . $value['disposal_sites']);
                $PHPSheet->setCellValue('N' . $i, '' . $value['routes']);
                $PHPSheet->setCellValue('O' . $i, '' . $value['start_time']);
                $PHPSheet->setCellValue('P' . $i, '' . $value['end_time']);
                $PHPSheet->setCellValue('Q' . $i, '' . count($plate_number));
                $PHPSheet->setCellValue('R' . $i, '' . implode(',',$plate_number));

                for ($col = 'A'; $col <= 'S'; $col++) {  
                    // 设置单元格的自动换行样式  
                    $PHPSheet->getStyle($col . $i)->applyFromArray($styleArray); 
                }  
                
                $i++;
            }
            for ($col = 'A'; $col <= 'S'; $col++) {  
                // 设置单元格的自动换行样式  
                $PHPSheet->getStyle($col . 2)->applyFromArray($styleArray); 
                $PHPSheet->getStyle($col . 3)->applyFromArray($styleArray); 
            }  
            // 最后，检查最后一个store_name的单元格是否需要合并（如果列表不以不同的store_name结束）  
            if ($lastStoreName != '') {  
                $PHPSheet->mergeCells('B' . $startRow . ':' . 'B' . ($i - 1));  
                $PHPSheet->getStyle('B' . $startRow)->applyFromArray($styleArray); 
            }  
           
            $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, "Excel2007");
            header('Content-Disposition: attachment;filename=' . $file_name);
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            $PHPWriter->save("php://output");
   
       
    }


}
